<template>
  <div class="department-container">
    <div class="app-container">
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <div slot="header">
          <PageTools>
            <template #left>目前总共{{ total }}位员工</template>
            <template #right>
              <el-button
                v-if="checkPoints('mm-mamihon')"
                type="primary"
                size="small"
                @click="$router.push('/import')"
              >
                导入excel
              </el-button>
              <el-button type="primary" size="small" @click="exportEmployees">
                导出excel
              </el-button>
              <el-button type="primary" size="small" @click="showDialog = true">
                新增员工
              </el-button>
            </template>
          </PageTools>
        </div>
        <!-- card body -->
        <!-- table列表 -->
        <!-- :default-sort可以指定当前页加载后,数据按照哪一列进行排序 -->
        <!-- prop指定排序列 order 排序方式 descending 降序 || ascending 升序 -->
        <el-table
          :data="list"
          border
          :default-sort="{ prop: 'workNumber', order: 'descending' }"
        >
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column>
            <!-- 显示员工头像 -->
            <template #default="{ row }">
              <el-image
                class="roundImg"
                :src="row.staffPhoto"
                fit="fill"
                @click="drawCode(row.staffPhoto)"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column label="聘用形式">
            <template #default="{ row }">
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <!-- sortable 开启当前列数据排序 => 前端假排序(只能排序一页的数据) -->
          <el-table-column sortable prop="timeOfEntry" label="入职时间">
            <template #default="{ row }">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态">
            <el-switch v-model="active"> </el-switch>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >
                查看
              </el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">
                分配角色
              </el-button>
              <el-button type="text" size="small" @click="delEmployees(row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="params.page"
            :page-size="params.size"
            :total="total"
            :page-sizes="[2, 5, 10]"
            layout="prev, pager, next, sizes"
            @current-change="changePage"
            @size-change="changeSize"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 新增员工弹层 -->
    <AddEmployee :show-dialog="showDialog" @close-dialog="showDialog = false" />
    <!-- 绘制头像二维码 -->
    <el-dialog
      title="头像二维码"
      :visible="showCode"
      width="30%"
      @close="showCode = false"
    >
      <el-row type="flex" justify="center">
        <canvas ref="cas"></canvas>
      </el-row>
    </el-dialog>
    <!-- 分配角色 -->
    <AssignRole ref="arole" :show-dialog.sync="showRole" />
  </div>
</template>

<script>
import QrCode from 'qrcode'
import { getEmployeeList, delEmployee } from '@/api/employees'
import AddEmployee from './components/add-employee.vue'
import dayjs from 'dayjs'
// 导入数据字典(枚举类型)
import dataTypes from '@/api/constant/employees'
import AssignRole from '@/views/employees/components/assign-role'
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data () {
    return {
      showRole: false,
      // 二维码弹层
      showCode: false,
      showDialog: false,
      // 账户状态
      active: true,
      // 员工列表
      list: [],
      // 分页参数
      params: {
        page: 1,
        size: 10
      },
      // 总条数
      total: 0
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 打开分配角色弹层
    assignRole (id) {
      this.showRole = true
      // 调用子组件方法获取当前用户角色数据回填
      this.$refs.arole.getUserRoles(id)
    },
    // 绘制头像二维码
    drawCode (photoUrl) {
      this.showCode = true
      // 打开弹层,DOM渲染(vue渲染html是异步的),所以下一行无法渲染出来
      // toCanvas(canvasDOM对象, 二维码包含的数据)
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.cas, photoUrl)
      })
    },
    // 导出员工列表的数据
    async exportEmployees () {
      // 懒加载语法(按需加载js模块)
      const excel = await import('@/utils/Export2Excel')
      const maps = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '工号': 'workNumber',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      // 导出头
      const header = Object.keys(maps)
      // 过滤头
      const filterHeader = Object.values(maps)
      // 转换二维数组
      const data = this.transformList(this.list, filterHeader)
      excel.export_json_to_excel({
        header,
        data,
        filename: 'testExport', // 导出下载文件的名字
        autoWidth: true, // excel单元格自适应宽度
        bookType: 'xlsx' // 导出文件的格式
      })
    },
    // 把list列表数据转换成二维数组
    transformList (list, filterHeader) {
      const secondArr = []
      list.forEach(item => {
        const newArr = []
        for (const key in item) {
          // 根据指定头 => 过滤数据
          if (filterHeader.includes(key)) {
            // 判断聘用形式 需要格式化 1 | 2
            if (key === 'formOfEmployment') {
              newArr.push(this.formatEmployment(item[key]))
            } else {
              newArr.push(item[key])
            }
          }
        }
        secondArr.push(newArr)
      })
      return secondArr
    },
    // 删除员工
    delEmployees (id) {
      this.$confirm('确认删除吗?', '提示').then(async () => {
        // 确认执行
        await delEmployee(id)
        this.$message.success('删除成功!')
        // 组件库BUG: 处理最后一页数据全部删除完列表页面正确,但数据显示还是之前那空的页
        // 1. 重新计算页码 => 公式: 总条数 - 1 / 每页条数 = 页码
        // 2. 和之前的页码做对比
        // : 条件: 之前页码 > 重新计算页码 => 修改页码
        const newPage = Math.ceil((this.total - 1) / this.params.size)
        // 页码>0 (默认页码最小是1)
        if (newPage > 0) {
          this.params.page = this.params.page > newPage ? newPage : this.params.page
        }
        this.getList()
      }).catch(console.log)
    },
    // 格式化入职时间
    formatDate (value, str = 'YYYY-MM-DD') {
      return dayjs(value).format(str)
    },
    // 格式化聘用形式
    formatEmployment (type) {
      const maps = {}
      dataTypes.hireType.forEach(item => {
        maps[item.id] = item.value
      })
      return maps[type]
    },
    // 切换每页多少条数据
    changeSize (size) {
      this.params.size = size
      this.getList()
    },
    // 分页切换列表数据
    changePage (newPage) {
      this.params.page = newPage
      this.getList()
    },
    // 获取员工数据
    async getList () {
      const { total, rows } = await getEmployeeList(this.params)
      // console.log(res)
      this.list = rows
      this.total = total
    }
  }
}
</script>

<style lang="scss" scoped>
.roundImg {
  width: 70px;
  height: 70px;
  border-radius: 100%;
}
</style>
